package com.qzdsoft.erpcloud.service.proj.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.qzdsoft.erpcloud.domain.proj.Bom;
import com.qzdsoft.erpcloud.domain.proj.BomItem;
import com.qzdsoft.erpcloud.domain.proj.MaterialInfo;
import com.qzdsoft.erpcloud.domain.proj.MaterialInfoKey;
import com.qzdsoft.erpcloud.domain.sys.LoginUser;
import com.qzdsoft.erpcloud.mapper.proj.BomInfoMapper;
import com.qzdsoft.erpcloud.mapper.proj.BomItemInfoMapper;
import com.qzdsoft.erpcloud.mapper.proj.BomItemMapper;
import com.qzdsoft.erpcloud.mapper.proj.BomMapper;
import com.qzdsoft.erpcloud.mapper.proj.MaterialInfoMapper;
import com.qzdsoft.erpcloud.service.proj.BomService;
import com.qzdsoft.erpcloud.vo.proj.BomDetailEditInfo;
import com.qzdsoft.erpcloud.vo.proj.BomDetailEditItemInfo;
import com.qzdsoft.erpcloud.vo.proj.BomInfo;
import com.qzdsoft.erpcloud.vo.proj.BomItemInfo;
import com.qzdsoft.erpcloud.vo.proj.BomQueryInfo;
import com.qzdsoft.utils.JsonUtils;
import com.qzdsoft.utils.StringUtil;
import com.qzdsoft.vo.LayTableResponse;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;

/**
 * Created by Admin
 */
@Service
public class BomServiceImpl implements BomService
{
    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(BomServiceImpl.class);
    @Autowired
    private BomMapper bomMapper;

    @Autowired
    private BomInfoMapper bomInfoMapper;

    @Autowired
    private BomItemMapper bomItemMapper;
    
    @Autowired
    private BomItemInfoMapper bomItemInfoMapper;

    @Autowired
    private MaterialInfoMapper materialInfoMapper;

    /**
     * 加载BOM网格数据
     * @see com.qzdsoft.erpcloud.service.proj.BomService#findPage(int, int)
     */
    @Override
    public LayTableResponse<BomInfo> findPage(int page, int limit)
    {
        PageHelper.startPage(page, limit);
        List<BomInfo> materialInfo = bomInfoMapper.findAll();
        LayTableResponse<BomInfo> po = new LayTableResponse<BomInfo>(
                materialInfo);
        return po;
    }
    /**
     * 根据查询条件查询父件网格信息
     * @see com.qzdsoft.erpcloud.service.proj.BomService#findPageByItems(com.qzdsoft.erpcloud.vo.proj.BomQueryInfo)
     */
    @Override
    public LayTableResponse<BomInfo> findPageByItems(BomQueryInfo search)
    {
        PageHelper.startPage(search.getPage(), search.getLimit());
        List<BomInfo> materialInfo = bomInfoMapper.findPageByItems(search);
        LayTableResponse<BomInfo> po = new LayTableResponse<BomInfo>(
                materialInfo);
        return po;
    }
    /**
     * 新增BOM父件信息
     * @throws Exception
     */
    @Override
    public Response<String> addBom(Bom bom, LoginUser loginUser) throws Exception
    {
        // 判断Form 提交是否为空
        if (bom == null)
        {
            throw new Exception("提交数据为空，不可保存！！");
        }
        // 设置公司ID
        bom.setCompanyId(1);
        // 设置创建人ID
        bom.setCreatorId(1);
        // 设置创建时间
        bom.setCtime(new Date());
        bom.setReviewStatus(false);
        bomMapper.insert(bom);
        return Response.success("新增BOM父件成功");
    }

    /**
     * 根据ID 查询父件BOM的视图信息（编辑BOM父件用）
     * @see com.qzdsoft.erpcloud.service.proj.BomService#getBomById(java.lang.Integer)
     */
    @Override
    public BomInfo getBomById(Integer id)
    {
        return this.bomInfoMapper.getBomById(id);
    }

    /**
     * 父件编辑保存
     */
    @Override
    public Response<String> editBom(Bom bom, LoginUser loginUser)
    {
        Bom searchbom = this.getById(bom.getId());
        if (searchbom == null)
        {
            return Response.error("BOM信息修改失败，当前BOM信息未找到！！");
        }
        MaterialInfoKey key = new MaterialInfoKey();
        key.setId(bom.getMaterialId());
        MaterialInfo material = this.materialInfoMapper.selectByPrimaryKey(key);
        searchbom.setCoding(material.getMaterialCoding());
        searchbom.setModifyId(1);
        searchbom.setModifyTime(new Date());
        searchbom.setName(bom.getName());
        searchbom.setSpec(bom.getSpec());
        searchbom.setIsDefault(bom.getIsDefault());
        searchbom.setIsNoUsed(bom.getIsNoUsed());
        searchbom.setLevel(bom.getLevel());
        searchbom.setMaterialId(bom.getMaterialId());
        searchbom.setMeasurementUId(bom.getMeasurementUId());
        searchbom.setRateFinish(bom.getRateFinish());
        searchbom.setRemark(bom.getRemark());
        searchbom.setVersion(bom.getVersion());
        bomMapper.updateByPrimaryKey(searchbom);
        return Response.success("BOM父件【名称：" + bom.getName() + " 版本号："
                + bom.getVersion() + "】修改成功");
    }

    /**
     * 根据ID 查询唯一一条父件信息
     */
    @Override
    public Bom getById(Integer id)
    {
        return this.bomMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据ID 查询唯一一条父件信息
     */
    @Override
    public BomItem getItemById(Integer id)
    {
        return this.bomItemMapper.selectByPrimaryKey(id);
    }

    /**
     * 删除物料信息
     */
    @Override
    public Response<String> delteBom(Integer id, LoginUser loginUser)
    {
        Bom searchbom = this.getById(id);
        if (searchbom == null)
        {
            return Response.error("物料信息删除失败，当前物料信息未找到！！");
        }
        return Response.success("物料信息删除成功");
    }

    /**
     * 新增BOM子件
     */
    @Override
    public Response<String> addChildBom(BomItem childbom, LoginUser loginUser)
    {
        // 设置公司ID
        childbom.setCompanyId(1);
        bomItemMapper.insert(childbom);
        return Response.success("新增BOM子件成功");
    }

    /**
     * 修改Bom子件
     */
    @Override
    public Response<String> editChildBom(BomItem bomchild, LoginUser loginUser)
    {
        int id = bomchild.getId();
        BomItem bomitem = this.getItemById(id);
        if (bomitem == null)
        {
            return Response.error("BOM信息修改失败，当前BOM信息未找到！！");
        }
        // 设置公司ID
        bomchild.setCompanyId(1);
        bomchild.setBomId(bomitem.getBomId());
        bomItemMapper.updateByPrimaryKey(bomchild);
        return Response.success("更新BOM子件成功");
    }

    /**
     * 获取jqgrid 存货信息数据
     */
    @Override
    public String getChildByBomId(int rows, int page, int BomId)
    {
        List<BomItem> materialList = bomItemMapper.findByBomid(BomId);
        if (materialList.size() <= 0)
        {
            String jsondata = "{\"page\":\"1\"," + " \"total\":2,"
                    + " \"records\":\"13\"," + " \"rows\":" + " [" + " {"
                    + " \"id\":\"13\"," + " \"cell\":"
                    + " [\"13\",\"2007-10-06\",\"Client 3\",\"1000.00\",\"0.00\",\"1000.00\",null]"
                    + " }," + " {" + " \"id\":\"12\"," + " \"cell\":"
                    + " [\"12\",\"2007-10-06\",\"Client 2\",\"700.00\",\"140.00\",\"840.00\",null]"
                    + " }," + " {" + " \"id\":\"11\"," + " \"cell\":"
                    + " [\"11\",\"2007-10-06\",\"Client 1\",\"600.00\",\"120.00\",\"720.00\",null]"
                    + " }," + " {" + " \"id\":\"10\"," + " \"cell\":"
                    + " [\"10\",\"2007-10-06\",\"Client 2\",\"100.00\",\"20.00\",\"120.00\",null]"
                    + " }," + " {" + " \"id\":\"9\"," + " \"cell\":"
                    + " [\"9\",\"2007-10-06\",\"Client 1\",\"200.00\",\"40.00\",\"240.00\",null]"
                    + " }," + " {" + " \"id\":\"8\"," + " \"cell\":"
                    + " [\"8\",\"2007-10-06\",\"Client 3\",\"200.00\",\"0.00\",\"200.00\",null]"
                    + " }," + " {" + " \"id\":\"7\"," + " \"cell\":"
                    + " [\"7\",\"2007-10-05\",\"Client 2\",\"120.00\",\"12.00\",\"134.00\",null]"
                    + " }," + " {" + " \"id\":\"6\"," + " \"cell\":"
                    + " [\"6\",\"2007-10-05\",\"Client 1\",\"50.00\",\"10.00\",\"60.00\",\"\"]"
                    + " }," + " {" + " \"id\":\"5\"," + " \"cell\":"
                    + " [\"5\",\"2007-10-05\",\"Client 3\",\"100.00\",\"0.00\",\"100.00\",\"no tax at all\"]"
                    + " }," + " {" + " \"id\":\"4\"," + " \"cell\":"
                    + " [\"4\",\"2007-10-04\",\"Client 3\",\"150.00\",\"0.00\",\"150.00\",\"no tax\"]"
                    + " }" + " ],"
                    + " \"userdata\":{\"amount\":3220,\"tax\":342,\"total\":3564,\"name\":\"Totals:\"}"
                    + " }";
            return jsondata;
        }
        else
        {
            int records = materialList.size();
            int total = records / rows + 1;

            StringBuilder sb = new StringBuilder();
            sb.append("{\"page\":").append("\"").append(page).append("\",")
                    .append("\"total\":").append("\"").append(total)
                    .append("\",").append("\"records\":").append("\"")
                    .append(records).append("\",").append("\"rows\":[");

            for (int i = (page - 1) * rows; (i < records)
                    && (i < page * rows); i++)
            {
                BomItem fiConfig = materialList.get(i);
                sb.append(JsonUtils.objectToJson(fiConfig));
                int j = i + 1;
                if ((j < records) && (j < page * rows))
                {
                    sb.append(",");
                }
            }
            sb.append("]}");
            System.out.println("&^^*^*^&(&(&*(&*&*T^&^++++=" + sb.toString());
            return sb.toString();
        }
    }

    /**
     * 删除物料信息子件
     */
    @Override
    public Response<String> delteBomItem(Integer id, LoginUser loginUser)
    {
        BomItem bomItem = this.getItemById(id);
        if (bomItem == null)
        {
            return Response.error("子件删除失败，当前子件信息未找到！！");
        }
        BomItem newbomItem = new BomItem();
        newbomItem.setId(id);
        bomItemMapper.deleteByPrimaryKey(id);
        return Response.success("删除成功");
    }

    /**
     * 删除整个物料信息
     * @param id
     * @param loginUser
     * @return
     */
    @Override
    public Response<String> delBomById(Integer id, LoginUser loginUser)
    {
        Bom bom = this.getById(id);
        List<BomItem> bomItem = this.bomItemMapper.findByBomid(id);
        if (bom == null)
        {
            return Response.error("BOM删除失败，当前BOM信息未找到，请检查逻辑！！");
        }
        else
        {
            // 存在子件 就删除所有子件后在删除父件
            if (bomItem.size() > 0)
            {
                this.bomItemMapper.deleteByBomId(id);
            }
            this.bomMapper.deleteByPrimaryKey(id);
            return Response.success("BOM【名称：" + bom.getName() + " 版本号："
                + bom.getVersion() + "】删除成功");
        }
    }
    /**
     * BOM审核
     * @see com.qzdsoft.erpcloud.service.proj.BomService#audtById(java.lang.Integer, com.qzdsoft.erpcloud.domain.sys.User)
     */
    @Override
    public Response<String> audtById(Integer id, LoginUser loginUser)
    {
        Bom searchbom = this.getById(id);
        if(searchbom==null){
            return  Response.error("审核失败，当前记录未找到！！");
        }
        searchbom.setReviewId(1);
        searchbom.setReviewStatus(true);
        searchbom.setReviewTime(new Date());
        this.bomMapper.updateByPrimaryKey(searchbom);
        return Response.success("BOM【名称：" + searchbom.getName() + " 版本号："
                + searchbom.getVersion() + "】审核成功");
    }
    /**
     * BOM弃审
     * @see com.qzdsoft.erpcloud.service.proj.BomService#unAudtById(java.lang.Integer, com.qzdsoft.erpcloud.domain.sys.User)
     */
    @Override
    public Response<String> unAudtById(Integer id, LoginUser loginUser)
    {
        Bom searchbom = this.getById(id);
        if(searchbom==null){
            return  Response.error("弃审失败，当前记录未找到！！");
        }
        searchbom.setReviewId(null);
        searchbom.setReviewStatus(false);
        searchbom.setReviewTime(null);
        this.bomMapper.updateByPrimaryKey(searchbom);
        return Response.success("BOM【名称：" + searchbom.getName() + " 版本号："
                + searchbom.getVersion() + "】弃审成功");
    }
    /**
     * 根据BOMID 查询所有的子件 单级展开
     * @see com.qzdsoft.erpcloud.service.proj.BomService#getBomChildByBomId(int)
     */
    @Override
    public List<BomItemInfo> getBomChildByBomId(int bomId,BomQueryInfo queryinfo){
        return this.bomItemInfoMapper.getBomChildByBomId(queryinfo);
    }
    
    /**
     * BOM子件 新增、修改 保存
     * @see com.qzdsoft.erpcloud.service.proj.BomService#bomitemedit(com.qzdsoft.erpcloud.vo.proj.BomDetailEditInfo)
     * TODO 缺少BOM闭环验证
     */
    @Transactional
    @Override
    public Response<String> bomitemedit(BomDetailEditInfo info)
    {
        logger.debug("编辑BOM子件详情提交数据为空{}",info);
        List<BomDetailEditItemInfo> details = info.getItems();
        if(CollectionUtils.isEmpty(details)) {
            logger.error("BOM子件详情提交数据为空");
            return new Response<>(ResultEnum.ERROR);
        }
        List<BomItem> adddetails = new ArrayList<BomItem>();//新增的BOM子件详情
        List<BomItem> editDetails = new ArrayList<BomItem>();//修改BOM子件详情
        for(BomDetailEditItemInfo d:details) {
            BomItem detail = new BomItem();
            if(!StringUtil.isEmpty(d.getId())) {
                detail = bomItemMapper.selectByPrimaryKey(d.getId());
                if(detail==null) {
                    logger.error("编辑BOM子件时,根据id,没找到相应的明细数据，可能改明细不存在",d.getId());
                    throw new RuntimeException("编辑BOM子件时,根据id,没找到相应的明细数据，可能改明细不存在");
                }
                detail.setModifyTime(new Date());
                editDetails.add(detail);
            }else {
                adddetails.add(detail);
            }
            Bom bom = bomMapper.selectByPrimaryKey(info.getBomId());
            if(bom==null) {
                logger.error("物料id，根据物料id：{},没找到对应的物料信息");
                throw new RuntimeException("物料id错误");
            }
            detail.setBomId(info.getBomId());
            detail.setCompanyId(info.getCompanyId());
            detail.setAttritionRate(d.getAttritionRate());
            detail.setDenominatorDosage(d.getDenominatorDosage());
            detail.setMaterialBomId(d.getMaterialBomId());
            detail.setMaterialInfoId(d.getMaterialInfoId());
            detail.setNumeratorDosage(d.getNumeratorDosage());
            detail.setProductionDosage(d.getProductionDosage());
            detail.setRemark(d.getRemark());
            detail.setRequirementDosage(d.getRequirementDosage());
        }
        int count = 0;
        if(!CollectionUtils.isEmpty(adddetails)) {
            count = bomItemMapper.insertList(adddetails);
            if(count!=adddetails.size()) {
                logger.error("编辑BOM子件明细错误，更新数据不对updatecount={},提交新增数据条数：{}",count,adddetails.size());
                throw new RuntimeException("编辑采购订单明细错误，更新数据不对updatecount="+count);
            }
        }
        
        count = 0;
        for(BomItem p:editDetails) {
            count += bomItemMapper.updateByPrimaryKey(p);
        }
        if(count!=editDetails.size()) {
            logger.error("编辑BOM子件明细错误，更新数据不对updatecount={},提交修改数据条数：{}",count,editDetails.size());
            throw new RuntimeException("编辑BOM子件明细错误，更新数据不对updatecount="+count);
        }
        return new Response<String>(ResultEnum.SUCCESS);
    }
    
    /**
     * 根据IDs 删除
     * @see com.qzdsoft.erpcloud.service.proj.BomService#removebomitem(java.util.List)
     */
    @Override
    public Response<String> removebomitem(List<Integer> ids)
    {
        int counts = bomItemMapper.deleteByIds(ids);
        //更新purchaseorder 里面统计信息
        if(counts!=ids.size()) {
            logger.error("编辑BOM子件明细错误，删除数据不对deletecount={},提交修改数据条数：{}",counts,ids.size());
            throw new RuntimeException("删除BOM子件明细错误，更新数据不对deletecount="+counts);
        }
        return new Response<String>(ResultEnum.SUCCESS);
    }
}